# time模块的time方法是一个保存到小数点七位的数据，统计从某个时间开始到现在的秒数，1585465982.1132941
# ctime一个日期加时间。Sun Mar 29 15:13:10 2020
from time import time

from rest_framework.throttling import BaseThrottle, SimpleRateThrottle

# VISIT_ADDR = {}
#
# class VisitLimit(BaseThrottle):
#     """每60秒只能访问4次"""
#
#     def __init__(self):
#         self.history = None
#
#     def allow_request(self,request,view):
#         # 1、获取用户IP
#         # remote_addr = request.META.get('REMOTE_ADDR')
#         remote_addr = self.get_ident(request)
#         # 说明这个ip第一次访问
#         if remote_addr not in VISIT_ADDR:
#             VISIT_ADDR[remote_addr] = [time(),]
#             return True
#         # 说明不是第一次访问
#         history = VISIT_ADDR.get(remote_addr)
#         self.history = history
#         # time.time()是以秒为单位的,减去60秒，可以传入60和4的不定值
#         while history and history[-1] < time() - 60:
#             history.pop()
#         if len(history) < 4:
#             history.insert(0,time())
#             return True
#
#     def wait(self):
#         # 自定义还需要等多少秒
#         return 60 - (time() - self.history[-1])


# TODO:以上drf已经帮我们实现了，只需继承SimpleRateThrottle,在配置文件指定频率就可以了

class VisitLimit(SimpleRateThrottle):
    """游客限流，频率读配置文件中的AnonVisitor"""
    scope = "AnonVisitor"

    def get_cache_key(self,request,view):
        return self.get_ident(request)

class UserLimit(SimpleRateThrottle):
    """登录用户限流，频率读配置文件中的UserVisitor"""

    scope = "UserVisitor"

    def get_cache_key(self,request,view):
        return self.get_ident(request)